package se.ytterman.jpcap.data.ip;

import java.lang.*;
import java.io.*;
import java.util.regex.*;

import se.ytterman.jpcap.data.bytearray.ArrayBinaryData;

public class IPV4Address extends ArrayBinaryData {

    public IPV4Address(byte[] byte_buffer) throws Exception {
	super(byte_buffer);

	if(byte_buffer.length != 4) {
	    throw new Exception("");
	}
    }

    public IPV4Address(InputStream packetInputStream) throws Exception {
	super(4, packetInputStream);
    }

    public IPV4Address(String ip_number) throws Exception {
	super(4);

	String ip_pattern = "([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})";
	Pattern p = Pattern.compile(ip_pattern);
	Matcher m = p.matcher(ip_number);

	// Perform basic check of format
	if(m.matches()) {
	    // Iterate and print...
	    for(int i = 1; i <= m.groupCount(); i++) {
		// Extract "byte" value for each part of the IP number
		int byte_value = Integer.parseInt(m.group(i), 10);
		
		// Check if valie is withing range (0-255) else throw
		if(byte_value >= 0 && byte_value <= 255) {
		    this.byte_buffer[i-1] = (byte)byte_value;
		}
		else {
		    // XXX Throw exception
		}
	    }
	}
	else {
	    // XXX Throw exception
	}
    }

    // toString
    public String toString() {
	String ip_str = String.format("%d.%d.%d.%d",
				       (int)(this.byte_buffer[0] & 0xFF),
				       (int)(this.byte_buffer[1] & 0XFF),
				       (int)(this.byte_buffer[2] & 0XFF),
				       (int)(this.byte_buffer[3] & 0XFF)
				       );

	return ip_str;
    }
}
